package kr.hkit.androidproject_caloriecheck;

import android.app.Fragment;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

public class HomeFragment extends Fragment {
	TextView basic;
	TextView eat;
	TextView totalEat;
	TextView exercise;
	ProgressBar mProgBar;
	ProgressBar mProgBar2;
	DAO dao;

	int eatKcal;

	int kcal;
	int eatSum;

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View root = inflater.inflate(R.layout.home, container, false);
		dao = DAO.open(getActivity());
		basic = (TextView) root.findViewById(R.id.basic);
		eat = (TextView) root.findViewById(R.id.eat);
		totalEat = (TextView) root.findViewById(R.id.total_eat);
		exercise = (TextView) root.findViewById(R.id.exercise);
		mProgBar = (ProgressBar) root.findViewById(R.id.progressBar1);
		mProgBar2 = (ProgressBar) root.findViewById(R.id.progressBar2);

		SharedPreferences pref = getActivity().getSharedPreferences("user", 0);
		kcal = pref.getInt("kcal", 0);
		basic.setText("권장량 " + String.valueOf(kcal) + "kcal");

		pref = getActivity().getSharedPreferences("num", 0);
		eatSum = pref.getInt("eatSum", 0);
		eat.setText("현재 섭취량 " + String.valueOf(eatSum) + "kcal");
		totalEat.setText("총 섭취량 " + String.valueOf(eatSum) + "kcal");

		int exerciseSum = pref.getInt("exerciseSum", 0);
		exercise.setText("현재 운동량 " + String.valueOf(exerciseSum) + "kcal");

		eatKcal = pref.getInt("eatKcal", 0);

		mProgBar.setMax(kcal);
		
		BackThread thread = new BackThread();
		thread.setDaemon(true);
		thread.start();

		return root;
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			int currentProgress = msg.arg1;

			
			if (msg.what == 0) {
				mProgBar.setProgress(currentProgress);
			}
		};
	};

	class BackThread extends Thread {
		public void run() {
			while(true){
				Message msg = mHandler.obtainMessage(0, eatSum, 0);
				mHandler.sendMessage(msg);
				if(eatSum >= kcal){
					break;
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}	
		}
	}
}
